<?php

session_start();
if (!isset($_POST["id"])) {
    header("Location: index.php");
    exit();
}
require_once 'database.php';
require_once 'formValidation.php';

//server side form validation
$idEquipa = $_POST["id"];
$login = $_POST["login"];
$equipa = $_POST["nome"];
$email = $_POST["email"];
$escola = $_POST["schoolname"];
$morada = $_POST["schooladdress"];
$localidade = $_POST["schoolcity"];
$codpostal = $_POST["schoolcode"];
$professor = $_POST["professor"];
$telefone = $_POST["schoolphone"];
$elementos = $_POST["elementos"];
if (isset($_FILES['avatar'])) {
    $avatar = $_FILES['avatar'];
}

$valid = FieldValidator::validateEmail($email) &&
        FieldValidator::validateTelefone($telefone) &&
        FieldValidator::validateCodPostal($codpostal) &&
        strlen($professor) > 0 &&
        strlen($elementos) > 0 &&
        strlen($escola) > 0 &&
        strlen($morada) > 0 &&
        strlen($localidade) > 0;

if ($idEquipa < 0) {
    $passwd = $_POST["password"];
    $valid = $valid && strlen($login) && strlen($equipa) > 0 && strlen($passwd) > 0;
    if (!$valid) {
        header("Location: register.php?valid=false");
        exit(0);
    }

    $db = new DBUnauthConnection();

    $passwd = hash("sha256", $passwd);

    $result = $db->inserirEquipa($login, $equipa, $passwd, $email, $escola, $morada, $localidade, $codpostal, $professor, $telefone, $elementos);
    if ($result) {
        header("Location: index.php?register=true");
    } else {
        header("Location: index.php?register=false");
    }
} else {

    if ($idEquipa != $_SESSION["idUser"] && !$_SESSION["admin"]) {
        header("Location: index.php");
        exit();
    }

    if (!$valid) {
        header("Location: fichaEquipa.php?id=$idEquipa&valid=false");
        exit(0);
    }

    if (isset($avatar)) {
        $validAvatar = FieldValidator::validateAvatar($avatar);
        if ($validAvatar) {
            $destino = "images/avatares/" . $idEquipa . $avatar['name'];
            $avatarUrl = "http://localhost/Matematrix/" . $destino;
            move_uploaded_file($avatar['tmp_name'], $destino);
        }
    }

    $db = new DBTeamConnection();
    if($avatarUrl){
        $db->alterarAvatar($idEquipa, $avatarUrl);
    }
        $result = $db->alterarFichaEquipa($idEquipa, $email, $escola, $morada, $localidade, $codpostal, $professor, $telefone, $elementos);
    
    if ($result) {
        header("Location: fichaEquipa.php?id=$idEquipa&updated=true");
    } else {
        header("Location: fichaEquipa.php?id=$idEquipa&updated=false");
    }
}

unset($db);
?>
